"use strict";
// const preferredDisplaySurface = document.getElementById("displaySurface");
const video = document.getElementById("gum-local");
const startButton = document.getElementById("startButton");
let pc;
// let sendChannel;
// let receiveChannel;
const signaling = new BroadcastChannel("webrtc");
signaling.onmessage = (e) => {
  switch (e.data.type) {
    case "offer":
      handleOffer(e.data);
      break;
    case "answer":
      handleAnswer(e.data);
      break;
    case "candidate":
      handleCandidate(e.data);
      break;
    // case "ready":
    //   // A second tab joined. This tab will enable the start button unless in a call already.
    //   if (pc) {
    //     console.log("already in call, ignoring");
    //     return;
    //   }
    //   startButton.disabled = false;
    //   break;
    case "bye":
      if (pc) {
        hangup();
      }
      break;

    // 画图
    case "draw":
      this.drawLine(...e.data.data, false);
      break;

    case "clear":
      this.clear(false);
    default:
      console.log("unhandled", e);
      break;
  }
};

if (
  adapter.browserDetails.browser === "chrome" &&
  adapter.browserDetails.version >= 107
) {
  // document.getElementById("options").style.display = "block";
} else if (adapter.browserDetails.browser === "firefox") {
  adapter.browserShim.shimGetDisplayMedia(window, "screen");
}

async function handleCandidate(candidate) {
  if (!pc) {
    console.error("no peerconnection");
    return;
  }
  if (!candidate.candidate) {
    await pc.addIceCandidate(null);
  } else {
    await pc.addIceCandidate(candidate);
  }
}

async function handleAnswer(answer) {
  if (!pc) {
    console.error("no peerconnection");
    return;
  }
  await pc.setRemoteDescription(answer);
}

function createPeerConnection() {
  pc = new RTCPeerConnection();
  pc.onicecandidate = (e) => {
    const message = {
      type: "candidate",
      candidate: null,
    };
    if (e.candidate) {
      message.candidate = e.candidate.candidate;
      message.sdpMid = e.candidate.sdpMid;
      message.sdpMLineIndex = e.candidate.sdpMLineIndex;
    }
    signaling.postMessage(message);
  };
  pc.ontrack = (e) => {
    console.log("e123", e);
    video.srcObject = e.streams[0];
  };
}

function receiveChannelCallback(event) {
  // receiveChannel = event.channel;
  // receiveChannel.onmessage = (e) => {
  //   console.log("reonmessage", e);
  // };
  // receiveChannel.onopen = (e) => {
  //   console.log("reonopen", e);
  // };
  // receiveChannel.onclose = (e) => {
  //   console.log("reonclose", e);
  // };
}

async function handleOffer(offer) {
  console.log("offer", offer);
  if (pc) {
    console.error("existing peerconnection");
    return;
  }
  await createPeerConnection();
  // pc.ondatachannel = receiveChannelCallback;
  await pc.setRemoteDescription(offer);
  const answer = await pc.createAnswer();
  signaling.postMessage({ type: "answer", sdp: answer.sdp });
  await pc.setLocalDescription(answer);
}

async function handleSuccess(stream) {
  startButton.disabled = true;
  // preferredDisplaySurface.disabled = true;
  video.srcObject = stream;
  await createPeerConnection();
  // sendChannel = pc.createDataChannel("sendDataChannel");
  // sendChannel.onopen = (e) => {
  //   console.log("onopen", e);
  // };
  // sendChannel.onmessage = (e) => {
  //   console.log("onmessage", e);
  // };
  // sendChannel.onclose = (e) => {
  //   console.log("onclose", e);
  // };
  // 处理视频
  stream.getTracks().forEach((track) => pc.addTrack(track, stream));

  const offer = await pc.createOffer();
  signaling.postMessage({
    type: "offer",
    sdp: offer.sdp,
  });
  await pc.setLocalDescription(offer);
  stream.getVideoTracks()[0].addEventListener("ended", () => {
    startButton.disabled = false;
    // preferredDisplaySurface.disabled = false;
    stream.getTracks().forEach((track) => track.stop());
    // 停止共享
    signaling.postMessage({
      type: "bye",
    });
  });
}

// 传数据
// function sendData(data) {
//   if (sendChannel) {
//     sendChannel.send(data);
//   } else {
//     receiveChannel.send(data);
//   }
//   console.log("Sent Data: " + JSON.stringify(data));
// }

function handleError(error) {
  errorMsg(`getDisplayMedia error: ${error.name}`, error);
}

function errorMsg(msg, error) {
  const errorElement = document.querySelector("#errorMsg");
  errorElement.innerHTML += `<p>${msg}</p>`;
  if (typeof error !== "undefined") {
    console.error(error);
  }
}

startButton.addEventListener("click", () => {
  const options = { audio: true, video: true };
  const displaySurface = "default";
  // preferredDisplaySurface.options[preferredDisplaySurface.selectedIndex]
  //   .value;
  if (displaySurface !== "default") {
    options.video = { displaySurface };
  }
  navigator.mediaDevices
    .getDisplayMedia(options)
    .then(handleSuccess, handleError);
});

if (navigator.mediaDevices && "getDisplayMedia" in navigator.mediaDevices) {
  startButton.disabled = false;
} else {
  errorMsg("getDisplayMedia is not supported");
}

async function hangup() {
  if (pc) {
    pc.close();
    pc = null;
  }
  // sendChannel = null;
  // receiveChannel = null;
}
